package com.oa.modules.approvalsec1.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.aiosign.base.FileItem;
import com.github.aiosign.client.SignClient;
import com.github.aiosign.client.support.DefaultSignClient;
import com.github.aiosign.module.request.*;
import com.github.aiosign.module.response.*;
import com.google.gson.Gson;
import com.oa.common.utils.MD5Util;
import com.oa.common.utils.PdfUtil;
import com.oa.common.utils.R;
import com.oa.modules.approvalsec1.entity.ExplorationCloudEntity;
import com.oa.modules.approvalsec1.entity.RoomStoreEntity;
import com.oa.modules.approvalsec1.service.RoomStoreService;
import com.oa.modules.approvalsec1.service.SignatureService;
import com.oa.modules.approvalsec1.socket.WebSocketServer;
import com.oa.modules.sys.controller.AbstractController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("signature")
@Api(tags = "电子签章")
public class SignatureController extends AbstractController {

    private static final String APP_ID = "866718625498288128";
    private static final String APP_SECRET = "blMMnsBTggnVWRogRv";

    private static final String URL = "https://dsjj.dezhou.gov.cn/dzyz/api";

    private static final Logger log = LoggerFactory.getLogger(SignatureController.class);

    private static SignClient signClient = new DefaultSignClient(URL, APP_ID, APP_SECRET);

    @Autowired
    private RoomStoreService roomStoreService;

    @Autowired
    private SignatureService signatureService;

    @Autowired
    private PdfUtil pdfUtil;


    @GetMapping("/test")
    @ApiOperation(value = "测试接口")
    public R test() throws IOException {
        List<Map<String, Object>> position = pdfUtil.getPosition("C:/Users/jimbo/Desktop/test.pdf");
        log.info("position>>>" + position);
        return R.ok();
    }

    /**
     * 获取token
     */
    public static String getToken() {

        TokenRequest tokenRequest = new TokenRequest(APP_ID, APP_SECRET);
        TokenResponse response = signClient.execute(tokenRequest);
        if (response.isSuccess()) {
            //System.out.println("获取token成功，响应值为"+response.getData());
            return response.getData().getAccessToken();
        }
        return null;
    }

    /**
     * 获取个人id
     */
    public static String getPersonId(String param, String token) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
        Gson gson = new Gson();
        String result = HttpRequest.post(URL + "/v1/user/personal/query-personal-user")
                .body(param)
                .header("Content-Type", "application/json")
                .header("token", token)
                .header("sign", encrypt(param))
                .execute()
                .body();

        Map reMap = gson.fromJson(result, Map.class);
        log.info("user/personal/query-personal-user接口返回数据-->" + result);
        if ("1000".equals(reMap.get("return_code")) && "0".equals(reMap.get("result_code"))) {
            Map data = (Map) reMap.get("data");
            return (String) data.get("user_id");
        }
        return null;
    }

    /**
     * 获取企业用户ID
     */
    public static String getCompanyPersonId(String param, String token) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
        Gson gson = new Gson();
        String result = HttpRequest.post(URL + "/v1/user/company/query-user")
                .body(param)
                .header("Content-Type", "application/json")
                .header("token", token)
                .header("sign", encrypt(param))
                .execute()
                .body();

        Map reMap = gson.fromJson(result, Map.class);
        log.info("user/company/query-user接口返回数据-->" + result);
        if ("1000".equals(reMap.get("return_code")) && "0".equals(reMap.get("result_code"))) {
            Map data = (Map) reMap.get("data");
            return (String) data.get("user_id");
        }
        return null;
    }

    /**
     * 获取签名印章信息
     */
    public static List<Map<String, Object>> getSealInfos(String param, String token) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
        Gson gson = new Gson();
        String result = HttpRequest.post(URL + "/v1/seal/getSealInfos")
                .body(param)
                .header("Content-Type", "application/json")
                .header("token", token)
                .header("sign", encrypt(param))
                .execute()
                .body();

        Map reMap = gson.fromJson(result, Map.class);
        log.info("seal/getSealInfos接口返回数据-->" + result);
        if ("1000".equals(reMap.get("return_code")) && "0".equals(reMap.get("result_code"))) {
            List<Map<String, Object>> data = (List<Map<String, Object>>) reMap.get("data");
            List<Map<String, Object>> reData = new ArrayList<>();
            if (data.size() > 0) {
                //循环遍历签名列表
                for (Map<String, Object> map : data) {
                    //取状态为1的数据
                    if ((Double) map.get("status") == 1) {
                        reData.add(map);
                    }
                }
                return reData;
            } else {
                return data;
            }
        }
        return null;
    }

    /**
     * 上传合同文件
     */
    public static String uploadContract(String userID, String fileName, String filePath) {

        FileUploadRequest fileUploadRequest = new FileUploadRequest();
        fileUploadRequest.setFileType("contract");
        fileUploadRequest.setFileName(fileName);
        fileUploadRequest.setUserId(userID);
        FileItem fileItem = new FileItem(new File(filePath));
        fileUploadRequest.setFileItem(fileItem);
        FileUploadResponse execute = signClient.execute(fileUploadRequest);
        log.info("响应状态：{}", execute.getResultCode());
        log.info("响应信息：{}", execute.getResultMessage());
        log.info("响应数据：{}", execute.getData());
        if (execute.isSuccess()) {
            //返回文件id
            return execute.getData().getFileId();
        }

        return null;
    }

    /**
     * 添加合同文件
     */
    public static String addContract(String name, String fileId, String userId) {

        ContractAddRequest contractAddRequest = new ContractAddRequest();
        // 合同名字
        contractAddRequest.setName(name);
        // 文件id
        contractAddRequest.setFileId(fileId);
        // 用户id不能为空
        contractAddRequest.setUserId(userId);
        // 描述信息
        contractAddRequest.setDescription("测试描述");
        ContractAddResponse execute = signClient.execute(contractAddRequest);
        log.info("响应状态：{}", execute.getResultCode());
        log.info("响应信息：{}", execute.getResultMessage());
        log.info("响应数据：{}", execute.getData());
        if (execute.isSuccess()) {
            //返回合同id
            return execute.getData().getContractId();
        }
        return null;
    }

    /**
     * 合同坐标签章接口
     */
    public static String signCommon(String contractId, String remark, String sealId, String userId) {

        CommonSignRequest commonSignRequest = new CommonSignRequest();
        // 合同id
        commonSignRequest.setContractId(contractId);
        // 签章备注
        commonSignRequest.setRemark(remark);
        // 签章信息集合
        CommonSignRequest.SignParams signParam = new CommonSignRequest.SignParams();
        // 印章id
        signParam.setSealId(sealId);
        // 第几页
        signParam.setPageNumber(1);
        // 水平横坐标
        signParam.setHorizontal(20.9);
        // 垂直纵坐标
        signParam.setVertical(28.8);
        // 印章宽度
        signParam.setWidth(40.0);
        // 印章高度
        signParam.setHeight(40.0);
        List<CommonSignRequest.SignParams> signParams = Collections.singletonList(signParam);
        commonSignRequest.setFields(signParams);
        // 用户id
        commonSignRequest.setUserId(userId);

        SignResponse execute = signClient.execute(commonSignRequest);
        log.info("响应状态：{}", execute.getResultCode());
        log.info("响应信息：{}", execute.getResultMessage());
        log.info("响应数据：{}", execute.getData());
        if (execute.isSuccess()) {
            //返回文件id
            return execute.getData().getFileId();
        }
        return null;
    }

    /**
     * 签多页
     * 需要传签章集合参数
     */
    public static String signCommons(String contractId, String remark, String sealId, String userId, List<Map<String, Object>> pList) {

        CommonSignRequest commonSignRequest = new CommonSignRequest();
        // 合同id
        commonSignRequest.setContractId(contractId);
        // 签章备注
        commonSignRequest.setRemark(remark);
        // 签章信息集合
        List<CommonSignRequest.SignParams> signParams = new ArrayList<>();
        //log.info("签章集合信息aaa"+pList);
        for (Map<String, Object> obj : pList) {
            //log.info("签章集合信息"+obj);
            CommonSignRequest.SignParams signParam = new CommonSignRequest.SignParams();
            // 印章id
            signParam.setSealId(sealId);
            // 第几页
            signParam.setPageNumber((Integer) obj.get("pageNumber"));
            // 水平横坐标
            signParam.setHorizontal((Double) obj.get("horizontal"));
            // 垂直纵坐标
            signParam.setVertical((Double) obj.get("vertical"));
            // 印章宽度
            signParam.setWidth(50.0);
            // 印章高度
            signParam.setHeight(50.0);
            //log.info("赋值后集合信息"+signParam);
            signParams.add(signParam);
        }

        commonSignRequest.setFields(signParams);
        // 用户id
        commonSignRequest.setUserId(userId);
        log.info("参数：{}",commonSignRequest.toString());
        SignResponse execute = signClient.execute(commonSignRequest);
        log.info("响应状态：{}", execute.getResultCode());
        log.info("响应信息：{}", execute.getResultMessage());
        log.info("响应数据：{}", execute.getData());
        if (execute.isSuccess()) {
            //返回文件id
            return execute.getData().getFileId();
        }
        return null;
    }

    /**
     * 获取用户详情信息
     */
    public static UserInfoResponse.UserInfoModule getUserInfo(String userId) {
        UserInfoRequest userInfoRequest = new UserInfoRequest();
        // 用户id
        userInfoRequest.setUserId(userId);
        UserInfoResponse execute = signClient.execute(userInfoRequest);
        log.info("响应状态：{}", execute.getResultCode());
        log.info("响应信息：{}", execute.getResultMessage());
        log.info("响应数据：{}", execute.getData());
        if (execute.isSuccess()) {
            UserInfoResponse.UserInfoModule data = execute.getData();
            return data;
        }
        return null;
    }

    /**
     * 获取企业用户详情信息
     */
    public static CompanyUserInfoResponse.CompanyUserInfoModule getCompanyUserInfo(String userId) {
        CompanyUserInfoRequest companyUserInfoRequest = new CompanyUserInfoRequest();
        // 用户id
        companyUserInfoRequest.setUserId(userId);
        CompanyUserInfoResponse execute = signClient.execute(companyUserInfoRequest);
        log.info("响应状态：{}", execute.getResultCode());
        log.info("响应信息：{}", execute.getResultMessage());
        log.info("响应数据：{}", execute.getData());
        if (execute.isSuccess()) {
            CompanyUserInfoResponse.CompanyUserInfoModule data = execute.getData();
            return data;
        }
        return null;
    }

    /**
     * 用户证书申请
     */
    public static String certApply(String userId) {
        UserIdentityRequest userIdentityRequest = new UserIdentityRequest();
        // 用户id
        userIdentityRequest.setUserId(userId);
        UserCertPrepareResponse execute = signClient.execute(userIdentityRequest);
        log.info("响应状态：{}", execute.getResultCode());
        log.info("响应信息：{}", execute.getResultMessage());
        log.info("响应数据：{}", execute.getData());
        if (execute.isSuccess()) {
            String prepare_id = (String) execute.getData().get("prepare_id");
            return prepare_id;
        }
        return null;
    }

    /**
     * 用户证书续期
     */
    public static String renewal(String userId) {
        CertRenewalRequest certRenewalRequest = new CertRenewalRequest();
        //用户id
        certRenewalRequest.setUserId(userId);
        CertRenewalResponse execute = signClient.execute(certRenewalRequest);
        log.info("响应状态：{}", execute.getResultCode());
        log.info("响应信息：{}", execute.getResultMessage());
        log.info("响应数据：{}", execute.getData());
        if (execute.isSuccess()) {
            String prepare_id = (String) execute.getData().get("prepare_id");
            return prepare_id;
        }
        return null;
    }

    /**
     * 下载文件
     */
    public static String downloadFile(String fileId, String fileName) throws FileNotFoundException {
        String baseUri = "/v1/file/download";
        String savePath = "/home/file/examination-approval-project/" + UUID.randomUUID() + "/";
//        String savePath = "D:/downloadFile/file/sign/"+UUID.randomUUID() + "/";
        File file = new File(savePath);
        file.mkdirs();
        fileName = fileName.replaceAll(".pdf", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm") + ".pdf");
        FileOutputStream out = new FileOutputStream(savePath + fileName);
        signClient.download(baseUri, fileId, out);
        return savePath + fileName;
    }

    /**
     * @param param id_number  签章类型为1个人时，传身份证号；2企业时，传统一信用代码
     *              user_name  签章类型为1个人时，传姓名；2企业时，传企业名称
     *              file       合同文件地址
     *              type      签章类型; 1个人2企业
     *              pageNumber  签章页码   int
     *              horizontal    签章横坐标  double
     *              vertical     签章纵坐标   double
     *              width   签章宽度   double
     *              hight    签章高度   double
     */
    @PostMapping("/sign")
    @ApiOperation(value = "签名")
    public R sign(@RequestBody Map<String, Object> param) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException, ParseException, FileNotFoundException {
        String id_number = (String) param.get("id_number");
        String user_name = (String) param.get("user_name");
        String file = (String) param.get("file");
        String type = (String) param.get("type");
        file = file.replaceAll("https://www.qhspj.com/", "/home/file");
        String fileName = "";
        if (!"".equals(file) && file != null) {
            String[] split = file.split("/");
            fileName = split[split.length - 1];
        }
        //获取token
        String token = getToken();
        log.info("personId>>>" + token);

        //获取userid
        String userId = "";
        LinkedHashMap<String, Object> map = new LinkedHashMap<>();
        map.put("id_number", id_number);
        map.put("user_name", user_name);
        Gson gson = new Gson();
        if ("1".equals(type)) {
            //个人
            userId = getPersonId(gson.toJson(map), token);
        }
        if ("2".equals(type)) {
            //企业
            userId = getCompanyPersonId(gson.toJson(map), token);
        }
        log.info("userId>>>" + userId);

        if (userId == null || "".equals(userId)) {
            //不存在，请创建
            return R.error("用户或企业不存在，请到小程序德州市电子印章系统注册，并提交签名或印章");
        }


        //获取印章签名ID
        String sealId = "";
        LinkedHashMap<String, Object> map2 = new LinkedHashMap<>();
        map2.put("user_id", userId);
        if (userId != null) {
            List<Map<String, Object>> sealInfos = getSealInfos(gson.toJson(map2), token);
            log.info("sealInfos>>>" + sealInfos);
            //存在多签名的默认取第一个
            if (sealInfos.size() > 0) {
                Map<String, Object> stringObjectMap = sealInfos.get(0);
                sealId = (String) stringObjectMap.get("seal_id");
            }
        }

        if (sealId == null || "".equals(sealId)) {
            //不存在，请创建
            return R.error("用户或企业签章不存在，请到小程序德州市电子印章系统提交签名或印章");
        }

        //获取用户详情信息，查看是否有证书，证书是否正常且在有效期内
        if ("1".equals(type)) {
            //个人
            UserInfoResponse.UserInfoModule userInfo = getUserInfo(userId);
            log.info("certInfo>>>" + userInfo.getCertInfo());
            if (userInfo.getCertInfo() == null) {
                //用户无证书
                String prepare_id = certApply(userId);
                log.info("prepare_id>>>" + prepare_id);
            } else {
                UserInfoResponse.UserInfoModule.CertInfo certInfo = userInfo.getCertInfo();

                String status = certInfo.getStatus();
                String endDate = certInfo.getEndDate();
                if ("0".equals(status)) {
                    //证书注销，申请证书
                    String prepare_id = certApply(userId);
                    log.info("prepare_id>>>" + prepare_id);
                }
                SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
                Date parse = format.parse(endDate);
                Date nowDate = new Date();
                if (nowDate.compareTo(parse) >= 0) {
                    //证书到期，续期
                    String prepare_id = renewal(userId);
                    log.info("prepare_id>>>" + prepare_id);
                }
            }
        }
        if ("2".equals(type)) {
            //企业
            CompanyUserInfoResponse.CompanyUserInfoModule companyUserInfo = getCompanyUserInfo(userId);
            log.info("companyUserInfo>>>" + companyUserInfo.getCertInfo());
            if (companyUserInfo.getCertInfo() == null) {
                //用户无证书
                String prepare_id = certApply(userId);
                log.info("prepare_id>>>" + prepare_id);
            } else {
                CompanyUserInfoResponse.CompanyUserInfoModule.CertInfo certInfo = companyUserInfo.getCertInfo();

                String status = certInfo.getStatus();
                String endDate = certInfo.getEndDate();
                if ("0".equals(status)) {
                    //证书注销，申请证书
                    String prepare_id = certApply(userId);
                    log.info("prepare_id>>>" + prepare_id);
                }
                SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
                Date parse = format.parse(endDate);
                Date nowDate = new Date();
                if (nowDate.compareTo(parse) >= 0) {
                    //证书到期，续期
                    String prepare_id = renewal(userId);
                    log.info("prepare_id>>>" + prepare_id);
                }
            }
        }

        //上传文件
        String fileid = uploadContract(userId, "合同文件", file);
        log.info("fileid>>>" + fileid);

        //添加合同
        String contractId = addContract("合同文件", fileid, userId);
        log.info("contractId>>>" + contractId);


        //签章签名
        //可定义签名大小，签名位置，签名页码
        String downfileid = signCommon(contractId, "合同文件签章", sealId, userId);
        log.info("downfileid>>>" + downfileid);

        //下载已签章签名的文件
        String path = downloadFile(downfileid, fileName);
        //path = path.replaceAll("/home/file", "http://47.104.163.214/");
        //https://www.qhspj.com/
        path = path.replaceAll("/home/file", "https://www.qhspj.com/");
        return R.ok().put("path", path);

    }

    /**
     * @param param room_id    房间号
     *              id_number  签章类型为1个人时，传身份证号；2企业时，传统一信用代码
     *              user_name  签章类型为1个人时，传姓名；2企业时，传企业名称
     *              file       合同文件地址
     *              type       签章类型; 1个人2企业
     *              pageNumber  签章页码   int
     *              horizontal    签章横坐标  double
     *              vertical     签章纵坐标   double
     *              width   签章宽度   double
     *              hight    签章高度   double
     */
    @PostMapping("/sign2")
    @ApiOperation(value = "签名")
    public R sign2(@RequestBody Map<String, Object> param) throws IOException, NoSuchAlgorithmException, InvalidKeyException, ParseException {
        String id_number = (String) param.get("id_number");
        String user_name = (String) param.get("user_name");
        String file = (String) param.get("file");
        String type = (String) param.get("type");
        String room_id = (String) param.get("room_id");
        //List<Map<String,Object>> pList = (List<Map<String, Object>>) param.get("pageData");

        file = file.replaceAll("https://www.qhspj.com/", "/home/file");
        List<Map<String, Object>> pList = pdfUtil.getPosition(file);
        log.info("position>>>" + pList);
        //存储签名之后的地址
        StringBuilder builder = new StringBuilder();
        String fileName = "";
        if (!"".equals(file) && file != null) {
            String[] split = file.split("/");
            fileName = split[split.length - 1];
        }
        //获取token
        String token = getToken();
        log.info("personId>>>" + token);

        //获取userid
        String userId = "";
        LinkedHashMap<String, Object> map = new LinkedHashMap<>();
        map.put("id_number", id_number);
        map.put("user_name", user_name);
        Gson gson = new Gson();
        if ("1".equals(type)) {
            //个人
            userId = getPersonId(gson.toJson(map), token);
        }
        if ("2".equals(type)) {
            //企业
            userId = getCompanyPersonId(gson.toJson(map), token);
        }
        log.info("userId>>>" + userId);

        if (userId == null || "".equals(userId)) {
            //不存在，请创建
            return R.error("用户或企业不存在，请到小程序德州市电子印章系统注册，并提交签名或印章");
        }


        //获取印章签名ID
        String sealId = "";
        LinkedHashMap<String, Object> map2 = new LinkedHashMap<>();
        map2.put("user_id", userId);
        if (userId != null) {
            List<Map<String, Object>> sealInfos = getSealInfos(gson.toJson(map2), token);
            log.info("sealInfos>>>" + sealInfos);
            //存在多签名的默认取第一个
            if (sealInfos.size() > 0) {
                Map<String, Object> stringObjectMap = sealInfos.get(0);
                sealId = (String) stringObjectMap.get("seal_id");
            }
        }

        if (sealId == null || "".equals(sealId)) {
            //不存在，请创建
            return R.error("用户或企业签章不存在，请到小程序德州市电子印章系统提交签名或印章");
        }

        //获取用户详情信息，查看是否有证书，证书是否正常且在有效期内
        if ("1".equals(type)) {
            //个人
            UserInfoResponse.UserInfoModule userInfo = getUserInfo(userId);
            log.info("certInfo>>>" + userInfo.getCertInfo());
            if (userInfo.getCertInfo() == null) {
                //用户无证书
                String prepare_id = certApply(userId);
                log.info("prepare_id>>>" + prepare_id);
            } else {
                UserInfoResponse.UserInfoModule.CertInfo certInfo = userInfo.getCertInfo();

                String status = certInfo.getStatus();
                String endDate = certInfo.getEndDate();
                if ("0".equals(status)) {
                    //证书注销，申请证书
                    String prepare_id = certApply(userId);
                    log.info("prepare_id>>>" + prepare_id);
                }
                SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
                Date parse = format.parse(endDate);
                Date nowDate = new Date();
                if (nowDate.compareTo(parse) >= 0) {
                    //证书到期，续期
                    String prepare_id = renewal(userId);
                    log.info("prepare_id>>>" + prepare_id);
                }
            }
        }
        if ("2".equals(type)) {
            //企业
            CompanyUserInfoResponse.CompanyUserInfoModule companyUserInfo = getCompanyUserInfo(userId);
            log.info("companyUserInfo>>>" + companyUserInfo.getCertInfo());
            if (companyUserInfo.getCertInfo() == null) {
                //用户无证书
                String prepare_id = certApply(userId);
                log.info("prepare_id>>>" + prepare_id);
            } else {
                CompanyUserInfoResponse.CompanyUserInfoModule.CertInfo certInfo = companyUserInfo.getCertInfo();

                String status = certInfo.getStatus();
                String endDate = certInfo.getEndDate();
                if ("0".equals(status)) {
                    //证书注销，申请证书
                    String prepare_id = certApply(userId);
                    log.info("prepare_id>>>" + prepare_id);
                }
                SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
                Date parse = format.parse(endDate);
                Date nowDate = new Date();
                if (nowDate.compareTo(parse) >= 0) {
                    //证书到期，续期
                    String prepare_id = renewal(userId);
                    log.info("prepare_id>>>" + prepare_id);
                }
            }
        }

        //上传文件
        String fileid = uploadContract(userId, fileName, file);
        log.info("fileid>>>" + fileid);

        //添加合同
        String contractId = addContract(fileName, fileid, userId);
        log.info("contractId>>>" + contractId);


        //签章签名
        //可定义签名大小，签名位置，签名页码
        String downfileid = null;
        if (pList.size() > 0) {
            downfileid = signCommons(contractId, "合同文件签名", sealId, userId, pList);
        } else {
            downfileid = signCommon(contractId, "合同文件签名", sealId, userId);
        }

        log.info("downfileid>>>" + downfileid);

        //下载已签章签名的文件
        String path = downloadFile(downfileid, fileName);
        //path = path.replaceAll("/home/file", "http://47.104.163.214/");
        //https://www.qhspj.com/
        path = path.replaceAll("/home/file", "https://www.qhspj.com/");

        if (path != null && !"".equals(path)) {

            ExplorationCloudEntity cloudEntity = signatureService.selectOne(room_id);
            if (cloudEntity.getSignPath() != null && !"".equals(cloudEntity.getSignPath())) {
                cloudEntity.setSignPath(cloudEntity.getSignPath() + "," + path);
            } else {
                cloudEntity.setSignPath(path);
            }
            signatureService.updateById(cloudEntity);
            RoomStoreEntity roomStore = roomStoreService.getOne(new LambdaQueryWrapper<RoomStoreEntity>().eq(RoomStoreEntity::getRoomNum, room_id));
            //发送给已签名的文件到后台
            WebSocketServer.sendMessage3(roomStore.getUserId(), path);
            return R.ok().put("path", path);
        }

        return R.ok().put("path", "");

    }


    public static String encrypt(String str) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKey = new SecretKeySpec(APP_SECRET.getBytes("utf-8"), "Hmac256");
        sha256_HMAC.init(secretKey);
        byte[] hash = sha256_HMAC.doFinal(str.getBytes("utf-8"));
        String encodeStr = Base64.encodeBase64String(hash);
        String encrypt = MD5Util.encrypt(encodeStr);
        return encrypt.toUpperCase();
    }


}
